from collections import OrderedDict

from goods.models import GoodsChannelGroup, GoodsChannel, GoodsCategory


def get_categories():
    """
    获取商品分类导航数据
    """
    # python原生的字典是无序的，当数据量大的时候可能乱序，所以要用collections模块下的有序字典
    categories_dict = OrderedDict()
    # 查询所有的频道
    # channels = GoodsChannel.objects.all().order_by('group_id', 'sequence')
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')  # 和上一句等价，如果查询所有并排序，直接order_by就行
    # 遍历每个频道
    for channel in channels:
        # 获取每个频道的group_id
        group_id = channel.group_id
        # 构建group的数据结构
        if group_id not in categories_dict:
            categories_dict[group_id] = {'channels': [], 'sub_cats': []}

        # 获取当前频道的category的一级对象
        # category = GoodsCategory.objects.get(id=channel.category_id)
        category = channel.category  # 和上一句等价
        categories_dict[group_id]['channels'].append({'id': category.id, 'name': category.name, 'url': channel.url})
        # 获取当前一级category对象的二级category列表
        sub_cats = category.subs.all()
        for sub_cat in sub_cats:
            categories_dict[group_id]['sub_cats'].append({
                'id': sub_cat.id,
                'name': sub_cat.name,
                'sub_cats': [{'id': s_c.id, 'name': s_c.name} for s_c in sub_cat.subs.all()]
            })

    return categories_dict

